import router from './router'
import store from './store'
import { getToken } from '@/utils/auth' // get token from cookie
const whiteList = ['/login','/home'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
    // set page title
    document.title = to.meta.title

    // determine whether the user has logged in
    const hasToken = getToken()
    if (hasToken) {
        if (to.path === '/login') {
            // if is logged in, redirect to the home page
            next({ path: '/' })
        } else {
            const hasGetUserInfo = store.getters.userInfo
            if (hasGetUserInfo) {
                next()
            } else {
                try {
                    // get user info
                    await store.dispatch('getUserInfo') // 请求获取用户信息
                    next({ ...to, replace: true })
                    // next()
                } catch (error) {
                    // remove token and go to login page to re-login
                    console.log(error);
                    // await store.dispatch('resetToken')
                    next(`/login?redirect=${to.path}`)
                }
            }
        }
    }
    else {
        /* has no token*/
        if (whiteList.indexOf(to.path) !== -1) {
            // in the free login whitelist, go directly
            next()
        } else {
            next(`/login?redirect=${to.path}`)
        }

    }
})